package com.phuc.game.tankshooter.sprite;

import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.modifier.AlphaModifier;
import org.anddev.andengine.entity.modifier.IEntityModifier;
import org.anddev.andengine.entity.modifier.ParallelEntityModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.util.MathUtils;
import org.anddev.andengine.util.constants.TimeConstants;
import org.anddev.andengine.util.modifier.IModifier;

import com.phuc.game.tankshooter.MainActivity;

public class TankDeadSprite extends AnimatedSprite implements TimeConstants {

	public static final int WIDTH = 100;
	public static final int HEIGHT = 100;
	
	Scene scene;
	boolean isRemoved;
	float alpha;
	int timeSmoke;
	float tileW;
	float tileH;

	public TankDeadSprite(float pX, float pY, float pTileWidth, float pTileHeight,
			TiledTextureRegion pTiledTextureRegion, float rotation, Scene scene) {
		super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion);
		tileW = pTileWidth;
		tileH = pTileHeight;
		this.scene = scene;
		alpha = 1.0f;
		isRemoved = false;
		this.setRotation(rotation);
		timeSmoke = 0;
		
		AlphaModifier modifier = new AlphaModifier(6.5f, 1f, 0.5f, new IEntityModifier.IEntityModifierListener() {
			@Override
			public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { }
			@Override
			public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
				MainActivity.getInstant().runFromUpdateThread(new Runnable() {
					@Override
					public void run() {
						TankDeadSprite.this.detachSelf();
						TankDeadSprite.this.setIgnoreUpdate(true);
						TankDeadSprite.this.clearEntityModifiers();
						TankDeadSprite.this.clearUpdateHandlers();
					}
				});
			} 
		});
		
		this.registerEntityModifier(new ParallelEntityModifier(modifier));
	}

	@Override
	public void onManagedUpdate(final float pSecondsElapsed) {
		super.onManagedUpdate(pSecondsElapsed);

		timeSmoke++;
		if (timeSmoke >= 30) {
			int xRandom = MathUtils.random(-35, 35);
			int yRandom = MathUtils.random(-35, 35);
			MainActivity.getInstant().getGamePlay().createSmoke(getX() + tileW / 2 + xRandom, getY() + tileH / 2 + yRandom, 1);
			timeSmoke = 0;
		}
	}
}
